#!/bin/bash

# Copyright 2019 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail

fix_mount() {
  # Necessary only when userns-remap is enabled on the host, but
  # harmless The binary /bin/mount should be owned by root and have
  # the setuid bit.
  chown root:root /bin/mount
  chmod -s /bin/mount

  # This is to workaround the following bug if AUFS driver is used.
  # https://github.com/moby/moby/issues/9547
  sync

  # Systemd-in-a-container should have read only /sys
  # https://www.freedesktop.org/wiki/Software/systemd/ContainerInterface/
  # However, we need other things from `docker run --privileged` ...
  # and this flag also happens to make /sys rw, amongst other things.
  mount -o remount,ro /sys

  # For mount propagation.
  mount --make-rshared /
}

fix_machine_id() {
  # Deletes the machine-id embedded in the node image and generates a
  # new one.  This is necessary because both kubelet and other
  # components like weave net use machine-id internally to distinguish
  # nodes.
  rm -f /etc/machine-id
  systemd-machine-id-setup
}

fix_product_name() {
  # This is a small fix to hide the underlying hardware and fix issue #426
  # https://github.com/kubernetes-sigs/kind/issues/426
  if [[ -f /sys/class/dmi/id/product_name ]]; then
    echo "docker" > /product_name
    mount -o ro,bind /product_name /sys/class/dmi/id/product_name
  fi
}

run_extra_init() {
  if [[ -d /usr/local/bin/extra-init ]]; then
    for script in "/usr/local/bin/extra-init/"*; do
      bash $script
    done
  fi
}

fix_mount
fix_machine_id
fix_product_name
run_extra_init

# We want the command (expected to be systemd) to be PID 1, so exec to
# it.
exec "$@"
